package com.ced.base.utils;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.BodyPart;
import javax.mail.Multipart;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class EmailUtil {

	protected transient final Logger log = LogManager.getLogger(this.getClass());
 
	public  boolean sendHtmlMail(String userEmail,String subject,String content) {
 
		try {
			String smtpServer=GlobalSettingBase.getSmtpServer(),
		       smtpPort=GlobalSettingBase.getSmtpPort(),
		       emailFromUserName=GlobalSettingBase.getEmailFromUserName(),
		       emailFromUserPassword=GlobalSettingBase.getEmailFromUserPassword();
		
			Properties properties = new Properties();
			properties.put("mail.smtp.host", smtpServer);
			properties.put("mail.transport.protocol", "smtp");
			properties.put("mail.smtp.auth", "true");
			properties.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory"); // 使用JSSE的SSL
			properties.put("mail.smtp.socketFactory.fallback", "false"); // 只处理SSL的连接,对于非SSL的连接不做处理
			properties.put("mail.smtp.port", smtpPort);
			properties.put("mail.smtp.socketFactory.port",smtpPort);
			Session session = Session.getInstance(properties);
			//session.setDebug(true);
			MimeMessage message = new MimeMessage(session);
			// 发件人
			Address address = new InternetAddress(emailFromUserName);
			message.setFrom(address);
			// 收件人
			Address toAddress = new InternetAddress(userEmail);
			message.setRecipient(MimeMessage.RecipientType.TO, toAddress); // 设置收件人,并设置其接收类型为TO
 
			// 主题message.setSubject(changeEncode(emailInfo.getSubject()));
			message.setSubject(subject);
			// 时间
			message.setSentDate(new Date());
 
			Multipart multipart = new MimeMultipart();
 
			// 创建一个包含HTML内容的MimeBodyPart
			BodyPart html = new MimeBodyPart();
			// 设置HTML内容
			html.setContent(content, "text/html; charset=utf-8");
			multipart.addBodyPart(html);
			// 将MiniMultipart对象设置为邮件内容
			message.setContent(multipart);
			message.saveChanges();
			
			Transport transport = session.getTransport("smtp");
			transport.connect(smtpServer, emailFromUserName, emailFromUserPassword);
			transport.sendMessage(message, message.getAllRecipients());
			transport.close();
		} catch (Exception e) {
			log.error("发送邮件失败",e);
			return false;
		}
 
		return true;
	}
	public static void main(String[] args) {
		 EmailUtil util = new EmailUtil();
			util.sendHtmlMail("3376235370@qq.com","ddd","dddd");
		}

}
